package com.yq.cns.ui.main.fragment.common

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yq.cns.config.LanguageConfig
import com.yq.cns.config.UserInfoManage
import com.yq.cns.net.NewsApiService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CommonNewsFragmentViewModel : ViewModel() {
    private val _viewState =
        MutableStateFlow<CommonNewsFragmentState>(CommonNewsFragmentState.Loading)
    val state = _viewState.asStateFlow()

    var pageIndex = 1;

    fun getNewsList(cname: String) {

        viewModelScope.launch {
            kotlin.runCatching {
                NewsApiService.getNewsList(
                    cname,
                    1,
                    LanguageConfig.cnsLanguage,
                    UserInfoManage.getUserInfo().userId
                ).fullData()
            }.onSuccess {
                _viewState.value = CommonNewsFragmentState.LoadDataSuccess(it)
                pageIndex++
            }.onFailure {
                _viewState.value = CommonNewsFragmentState.Error(it.message!!)
            }

        }
    }

    fun getNewsListMore(cname: String) {
        viewModelScope.launch {
            kotlin.runCatching {
                NewsApiService.getNewsList(
                    cname, pageIndex,
                    LanguageConfig.cnsLanguage,
                    UserInfoManage.getUserInfo().userId
                ).fullData()
            }.onSuccess {
                _viewState.value = CommonNewsFragmentState.LoadMoreDataSuccess(it)
                pageIndex++
            }.onFailure {
                _viewState.value = CommonNewsFragmentState.LoadMoreDataFail(it.message.toString())
            }
        }
    }
}